package com.lifu.yygh.user.api;

import com.alibaba.fastjson.JSONObject;
import com.lifu.yygh.common.exception.YyghException;
import com.lifu.yygh.common.helper.JwtHelper;
import com.lifu.yygh.common.result.Result;
import com.lifu.yygh.common.result.ResultCodeEnum;
import com.lifu.yygh.model.user.UserInfo;
import com.lifu.yygh.user.service.UserInfoService;
import com.lifu.yygh.user.utils.HttpClientUtil;
import com.lifu.yygh.user.utils.WeixinConstantPropertiesUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Author lifu
 * @Date 2021/5/20 15:46
 */
@Controller
@RequestMapping(value = "/api/ucenter/wx")
public class WeixinApiController {
    @Autowired
    private UserInfoService userInfoService;

    //生成微信扫描二维码
    @GetMapping(value = "/getLoginParam")
    @ResponseBody
    public Result genQrConnect(){
        Map<String,Object> map = new HashMap<>();
        map.put("appid", WeixinConstantPropertiesUtil.WX_OPEN_APP_ID);
        map.put("scope","snsapi_login");
        String redirectUri = null;
        try {
            redirectUri = URLEncoder.encode(WeixinConstantPropertiesUtil.WX_OPEN_REDIRECT_URL, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        map.put("redirectUri", redirectUri);
        map.put("state", System.currentTimeMillis()+"");
        return Result.ok(map);
    }
    //微信扫描后回调的方法
    @GetMapping(value = "/callback")
    public String callback(String code, String state){
        if (StringUtils.isEmpty(state) || StringUtils.isEmpty(code)) {
            throw new YyghException(ResultCodeEnum.ILLEGAL_CALLBACK_REQUEST_ERROR);
        }
        //用code app_id 和密钥app_secret请求微信地址
        //%s类似于占位符
        StringBuffer baseAccessTokenUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");
        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(),
                WeixinConstantPropertiesUtil.WX_OPEN_APP_ID,
                WeixinConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                code);
        String result = null;
        //使用httpclient请求地址
        try {
            result = HttpClientUtil.get(accessTokenUrl);
        } catch (Exception e) {
            throw new YyghException(ResultCodeEnum.FETCH_ACCESSTOKEN_FAILD);
        }
        //从返回的字符串获取两个值，openid access_token
        JSONObject resultJson = JSONObject.parseObject(result);
        String accessToken = resultJson.getString("access_token");
        String openId = resultJson.getString("openid");

        //判断数据库中是否存在微信的扫描人信息
        //根据openid判断
        UserInfo userInfo = userInfoService.selectWxInfoOpenId(openId);
        if(userInfo == null){
            //数据库不存在微信信息，调用微信官方的接口
            //根据openid access_token获取微信用户的基本信息
            StringBuffer baseUserInfoUrl = new StringBuffer()
                    .append("https://api.weixin.qq.com/sns/userinfo")
                    .append("?access_token=%s")
                    .append("&openid=%s");
            String userInfoUrl = String.format(baseUserInfoUrl.toString(),accessToken,openId);
            String resultUserInfo = null;
            try {
                resultUserInfo = HttpClientUtil.get(userInfoUrl);
            } catch (Exception e) {
                throw new YyghException(ResultCodeEnum.FETCH_USERINFO_ERROR);
            }
            //解析用户信息
            JSONObject resultUserInfoJson = JSONObject.parseObject(resultUserInfo);
            String nickname = resultUserInfoJson.getString("nickname");
            String headimgurl = resultUserInfoJson.getString("headimgurl");
            //将扫描人信息添加到数据库
            userInfo = new UserInfo();
            userInfo.setOpenid(openId);
            userInfo.setNickName(nickname);
            userInfo.setStatus(1);
            userInfoService.save(userInfo);
        }
        //返回name和token
        Map<String,String> map = new HashMap<>();
        String name = userInfo.getName();
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        map.put("name", name);
        //用于前端判断是否需要绑定手机号
        if(StringUtils.isEmpty(userInfo.getPhone())) {
            map.put("openid", userInfo.getOpenid());
        } else {
            map.put("openid", "");
        }
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token", token);
        try {
            //跳转到前端页面
            return "redirect:" + WeixinConstantPropertiesUtil.YYGH_BASE_URL + "/weixin/callback?token="+map.get("token")+"&openid="+map.get("openid")+"&name="+URLEncoder.encode((String)map.get("name"),"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }
}
